package com.telife.component;

import com.telife.Main;
import javafx.animation.KeyFrame;
import javafx.animation.Timeline;
import javafx.beans.property.ReadOnlyDoubleProperty;
import javafx.geometry.Insets;
import javafx.geometry.Pos;
import javafx.scene.Node;
import javafx.scene.control.*;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.layout.VBox;
import javafx.util.Duration;

import java.net.URL;

/**
 * @author york
 * @since 2020/6/9
 */
public class ProcessDialog {

    /**
     * 饼状图进度条
     */
    private ProgressIndicator progressIndicator;

    private Dialog<Void> dialog;

    private Label tip;

    private VBox vBox;

    public ProcessDialog() {
        progressIndicator = new ProgressIndicator(-1);
        dialog = new Dialog<>();
        dialog.initOwner(Main.getStage());
        tip = new Label("正在加载应用");
        vBox = new VBox();
    }

    /**
     * 显示对话框
     */
    public void showDialog() {
        dialog.setTitle("温馨提示");

        //设置按钮类型
        ButtonType hiddenButtonType = new ButtonType("隐藏窗口", ButtonBar.ButtonData.OK_DONE);
        dialog.getDialogPane().getButtonTypes().add(hiddenButtonType);

        //隐藏按钮
        Node hiddenButton = dialog.getDialogPane().lookupButton(hiddenButtonType);
        hiddenButton.setVisible(false);

        //点击右上角关闭按钮后，关闭进度对话框
        dialog.setOnCloseRequest(event -> dialog.close());

        //自定义对话框的视图内容
        vBox.setAlignment(Pos.CENTER);
        vBox.setPadding(new Insets(40, 20, 0, 20));
        vBox.getChildren().add(progressIndicator);
        vBox.getChildren().add(tip);
        VBox.setMargin(tip, new Insets(20, 0, 0, 0));
        dialog.getDialogPane().setContent(vBox);

        //显示对话框
        dialog.show();
    }

    /**
     * 显示对话框并绑定进程
     * @param property
     */
    public void showDialog(ReadOnlyDoubleProperty property){
        this.showDialog();
        progressIndicator.progressProperty().bind(property);
    }

    /**
     * 关闭进度对话框
     */
    public void closeDialog() {
        if (dialog.isShowing()) {
            dialog.close();
        }
    }

    /**
     * 进度对话框显示加载完成并且定时关闭它
     * @param delayTime 几秒后关闭，单位是毫秒ms
     */
    public void showLoadDoneAndClose(long delayTime){
        URL url = getClass().getClassLoader().getResource("resources/icon/done.png");
        ImageView imageView = new ImageView();
        Image image = new Image(url.toExternalForm());
        imageView.setImage(image);
        vBox.getChildren().set(0,imageView);
        tip.setText("加载完成");

        //定时任务，关闭进程对话框
        Timeline closeTask = new Timeline(new KeyFrame(Duration.millis(delayTime), actionEvent -> closeDialog()));
        closeTask.play();

    }

}
